package ch.bfh.swos.learnaid.service.impl;

import java.lang.reflect.Type;
import java.util.Collection;

import javax.inject.Inject;
import javax.inject.Named;

import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;

import ch.bfh.swos.learnaid.model.Answer;
import ch.bfh.swos.learnaid.repository.AnswerRepository;
import ch.bfh.swos.learnaid.service.AnswerService;
import ch.bfh.swos.learnaid.service.dto.AnswerDTO;

@Named
public class DefaultAnswerService implements AnswerService {

    @Inject
    private AnswerRepository answerRepository;

    private final ModelMapper mapper = new ModelMapper();

    @Override
    public AnswerDTO create(AnswerDTO answerDTO) {
        Answer answer = mapper.map(answerDTO, Answer.class);
        Answer persistAnswer = answerRepository.save(answer);
        return mapper.map(persistAnswer, AnswerDTO.class);
    }

    @Override
    public AnswerDTO read(long id) {
        Answer answer = answerRepository.findOne(id);
        if (answer != null) {
            return mapper.map(answer, AnswerDTO.class);
        }
        return null;
    }

    @Override
    public Collection<AnswerDTO> list() {
        Iterable<Answer> answers = answerRepository.findAll();
        Type listType = new TypeToken<Collection<AnswerDTO>>() {
        }.getType();
        return mapper.map(answers, listType);
    }

    @Override
    public AnswerDTO update(AnswerDTO answerDTO) {
        Answer answer = mapper.map(answerDTO, Answer.class);
        Answer updatedAnswer = answerRepository.save(answer);
        return mapper.map(updatedAnswer, AnswerDTO.class);
    }

    @Override
    public void delete(AnswerDTO answerDTO) {
        Answer answer = answerRepository.findOne(answerDTO.getId());
        answerRepository.delete(answer);
    }

}
